#include "precompiled.h"
#include "contextimpl.h"
#include <core/entityobject.h>
#include "engine.h"
#include "windowsmanager.h"
#include "scriptenvironmentex.h"
#include "tasks.h"
#include "plugins.h"
#include "configstack.h"

#include <helpers/support/environment.h>
#include "helper.h"
#include "declarativeenvironmentex.h"
#include <extensions/plugin.h>

class ContextImplPrivate{
public:
	ContextImplPrivate() {}
	~ContextImplPrivate() {}
};

ContextImpl::ContextImpl(const QDir& baseDir):
	O_PRIVATE_CREATE(ContextImpl)
{
	process(baseDir);
}

ContextImpl::ContextImpl(Opl::Core::EntityObject *parent) :
		Optra::Extensions::Context(parent), O_PRIVATE_CREATE(ContextImpl)
{

}


ContextImpl::ContextImpl(Optra::Extensions::ZoneInterface* inf, Opl::Core::EntityObject *parent) :
		Optra::Extensions::Context(inf, parent), O_PRIVATE_CREATE(ContextImpl)
{
	//	O_D(Context);
}


void ContextImpl::registerWindow(Optra::Extensions::MainWindow* wnd)
{
    Q_ASSERT(wnd);
    Engine::instance()->windowsManager()->addWindow(wnd);
}

ContextImpl::~ContextImpl()
{
	O_PRIVATE_DELETE;
}

Opl::Scripting::ScriptEnvironment* ContextImpl::scripts()
{
	return new ScriptEnvironmentEx(ScriptEnvironmentEx::full, this);
}

bool ContextImpl::start(Opl::Core::Task* task, bool autodelete, QString name/* = QString()*/)
{
	return Engine::instance()->tasks()->start(task, autodelete, name);
}

bool ContextImpl::start(Opl::Core::Task* task, QString name/* = QString()*/)
{
	return Engine::instance()->tasks()->start(task, name);
}

Optra::Extensions::Plugin* ContextImpl::loadPlugin(const QString file)
{
	Optra::Extensions::Plugin* plg = Plugins::fromFile(file);
	return plg;
}

void ContextImpl::process(const QDir& root, bool createIfNeeded/* = false*/)
{
    setRootDir(root);

    QDir dir = root;

    if (!dir.exists("config") && createIfNeeded){
        dir.mkdir("config");
    }

    if (dir.cd("config")){
        ConfigStack * cfg = new ConfigStack;
        cfg->addFile(dir.absoluteFilePath("global.cfg"), true);
        cfg->addFile(dir.absoluteFilePath("user.cfg"), false);
        cfg->load();
        setConfig(cfg);
        setConfigDir(dir);
        dir.cdUp();
    }

    if (dir.cd("bin")){
        setBinDir(dir);
        dir.cdUp();
    }

    if (!dir.exists("resources") && createIfNeeded){
        dir.mkdir("resources");
    }

    if (dir.cd("resources")){
        setResourcesDir(dir);
        dir.cdUp();
    }
}

